const fs = require('fs');
const images = require("images");
const texturePath = "./res/";   //图集资源路径 存放 json 图集
const imgPath = "./res2/";      //拆分后的散图存储路径
const imgType = ["png", "jpg"]  //要支持的图集格式
var imageFile = null;           //当前正在拆分的图集文件
function start() {
    fs.readdir(texturePath, function (err, files) {
        for (var i = 0; i < files.length; i++) {
            console.log("进度：" + (i + 1) + "/" + files.length, "  正在处理:" + files[i])
            var path = files[i].split('.')
            const type = path[1];
            const fileName = path[0];
            if (type != 'json') {
                continue;
            }
            for (var k in imgType) {
                if (fs.existsSync(texturePath + fileName + '.' + imgType[k])) {
                    imageFile = texturePath + fileName + '.' + imgType[k];
                    break;
                }
            }
            if (!imageFile) {
                console.log("没有找到" + files[i] + "对应的图集，跳过")
                continue
            }
            //创建散图存储路径，已存在则先删除
            if (!fs.existsSync(imgPath)) {
                fs.mkdirSync(imgPath);
            }
            if (fs.existsSync(imgPath + fileName)) {
                rmFold(imgPath + fileName);
            }
            fs.mkdirSync(imgPath + fileName);
            //读取该图集JSON准备拆分
            const fileData = JSON.parse(fs.readFileSync(texturePath + files[i], 'utf-8'));
            const frames = fileData['frames'];
            for (let k in frames) {
                genImg(fileName, k, frames[k]['frame'], frames[k]['spriteSourceSize'], frames[k]['sourceSize']);
            }
        }
    })


}

//plist 暂未修复，需要的自行修复
function convertPlist() {
    var parseString = require('xml2js').parseString;
    var xml = fs.readFileSync(file, 'utf-8');

    parseString(xml, function (err, result) {
        //console.log(result.plist.dict[0].dict[0].dict[0].string);
        //  console.log(result.plist.dict[0].dict[0].dict[0].false);

        const name = result.plist.dict[0].dict[0].key;
        const dict = result.plist.dict[0].dict[0].dict;

        name.forEach((k, v) => {
            let str = dict[v].string[3];
            const boo = dict[v].true;
            str = str.replace(/[^0-9]+/ig, ",")
            const arr = str.split(',');
            let w, h;
            if (boo) {
                w = +arr[4],
                    h = +arr[3]
            } else {
                w = +arr[3],
                    h = +arr[4]
            }

            const info = {
                x: +arr[1],
                y: +arr[2],
                w: w,
                h: h
            }
            genImg(k, info);
        })
    });
    // fs.writeFileSync('./bbb.json', JSON.stringify(json, null, 4))
}

function genImg(fileName, k, info, spriteSourceSize, sourceSize) {

    //创建一个原图尺寸的空白图
    const canvas = images(sourceSize.w, sourceSize.h)
    //把原图从图集中扣出来
    const img = images(images(imageFile), info.x, info.y, info.w, info.h)
    //抠出来的图重叠到空白图上，并补偿偏移量
    canvas.draw(img, spriteSourceSize.x, spriteSourceSize.y).save(imgPath + fileName + '/' + k, { //Save the image to a file, with the quality of 50
        quality: 50
    });
}

//删除某个文件夹
function rmFold(srcPath) {
    let allFiles = [];
    function recurse(path) {
        let files = [];
        if (fs.existsSync(path)) {
            files = fs.readdirSync(path);
            files.forEach(function (file, index) {
                let curPath = path + "/" + file;
                if (fs.statSync(curPath).isDirectory()) { // recurse
                    recurse(curPath);
                } else { // del file
                    allFiles.push(curPath);
                    fs.unlinkSync(curPath)
                }
            });
            path != srcPath && fs.rmdirSync(path);
        }
    }
    recurse(srcPath);
    fs.rmdirSync(srcPath);
    return allFiles;
};

module.exports = start;
if (require.main == module) {
    start();
}